﻿#include "imageviewer.h"
#include "ui_imageviewer.h"

ImageViewer::ImageViewer(QWidget *parent, const QString &label) :
    QDialog(parent),
    _label(label),
    ui(new Ui::ImageViewer)
{
    ui->setupUi(this);

    table=TD_PRODUCT_IMG;
    setWindowTitle(_label);
    getImageList(_label);
}

ImageViewer::~ImageViewer()
{
    delete ui;
}

bool ImageViewer::isEmpty()
{
    return imgList.isEmpty();
}

void ImageViewer::viewFirst()
{
    showPixmap(imgList.first());
}

void ImageViewer::showPixmap(const QString &filePath)
{
    imgLocator=filePath;
    if(!QFile::exists(imgLocator))
        return;

    if(pix.load(imgLocator))
        ui->display->setPixmap(pix);

    if(!ui->status->text().isEmpty())
        ui->status->clear();
}

void ImageViewer::playNext()
{
    if(imgList.size() <= 1)
        return;

    QString filePath;
    int index=imgList.indexOf(imgLocator);
    if(index < imgList.size() -1)
        filePath=imgList.at(index + 1);
    else if(index == imgList.size() -1)
        filePath=imgList.first();

    showPixmap(filePath);
}

void ImageViewer::playPrevious()
{
    if(imgList.size() <= 1)
        return;

    QString filePath;
    int index=imgList.indexOf(imgLocator);
    if(index > 0)
        filePath=imgList.at(index - 1);
    else if(index == 0)
        filePath=imgList.last();

    showPixmap(filePath);
}

void ImageViewer::getImageList(const QString &label)
{
    if(!imgList.isEmpty())
        imgList.clear();

    QSqlQuery query;
    QString sql=QString("select detail,addition from %1 where label = '%2'").arg(table).arg(label);
    query.exec(sql);

    while(query.next())
    {
        QString detail=query.value("detail").toString();
        QString addition=query.value("addition").toString();
        if(addition == P_CDN)
            continue;
        else if(addition == P_IMG)
            detail=P_DIR_IMG + detail;

        imgList.append(detail);
    }
}

void ImageViewer::resizeEvent(QResizeEvent *)
{
    if(pix.isNull())
        return;

    QPixmap img;
    int width=ui->display->width();
    if(width <= pix.width())
        img=pix.scaledToWidth(ui->display->width());
    else
        img=pix;

    ui->display->setPixmap(img);
}

void ImageViewer::mouseDoubleClickEvent(QMouseEvent *)
{
    if(pix.isNull())
        return;

    qApp->clipboard()->setPixmap(pix);
    ui->status->setText(QStringLiteral("图片已复制到剪贴板"));
}

void ImageViewer::wheelEvent(QWheelEvent *event)
{
    if(imgLocator.isEmpty())
        return;

    QPoint value=event->angleDelta();

    //up
    if(value.y() > 0)
        playPrevious();

    //down
    else if(value.y() < 0)
        playNext();
}
